import router from './router';
import { getToken, getUserPermission, removeAll } from '@/utils/cache';
import { asyncRoutes, redirectPage, resetRouter } from '@/router';
import { filterPerRouter } from '@/utils';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import store from '@/store';

NProgress.configure({
  showSpinner: false
});

const whiteRouter = ['/login', '/404']; // 白名单路由

const toLogout = (next) => {
  const yhzxUrl = sessionStorage.getItem('yhzx_url');
  removeAll();
  if (yhzxUrl) {
    window.location.href = yhzxUrl;
  } else {
    if (next) {
      next('/login?token=');
    } else {
      resetRouter();
    }
  }
};

const matchRouter = () => {
  return new Promise((resolve, reject) => {
    const userRight = getUserPermission();
    if (userRight.length) {
      const currentUserMenu = filterPerRouter(asyncRoutes, userRight);
      currentUserMenu.push(redirectPage);
      router.addRoutes(currentUserMenu);
      store.commit('permission/updateRoutes', currentUserMenu);
      resolve(currentUserMenu);
    } else {
      setTimeout(toLogout, 1000);
      return;
    }
  });
};

router.beforeEach(async(to, from, next) => {
  NProgress.start();
  const hasToken = getToken();
  if (hasToken) {
    if (to.path === '/login') {
      const defaultModule = store.state.permission.accessRoutes[0];
      if (defaultModule.path === '*') { // 重定向404
        toLogout();
      } else if (defaultModule.path === '/') {
        if (defaultModule.children && defaultModule.children.length && defaultModule.children[0].path === '/') {
          next('/');
        } else {
          next(defaultModule.path + defaultModule.children[0].path);
        }
      } else {
        if (defaultModule.children && defaultModule.children.length && defaultModule.children[0].path === '/') {
          next(`${defaultModule.path}/${defaultModule.children[0].path}`);
        } else {
          next(`${defaultModule.path}`);
        }
      }
    } else {
      if (store.state.permission.accessRoutes.length) {
        next();
      } else {
        await matchRouter();
        next({ ...to, replace: true });
      }
    }
  } else {
    if (whiteRouter.includes(to.path)) {
      next();
    } else {
      toLogout(next);
    }
  }
});

router.afterEach(() => NProgress.done());
